package com.jay.net.clazz.socket.options;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Backlog {
	public static void main(String[] args) throws IOException {
		new Thread(new ServerBackLog()).start();
		new Thread(new ClientBackLog()).start();
	}
}

class ClientBackLog implements Runnable {
	public void run() {
		final int length = 100;
		String host = "localhost";
		int port = 8000;
		Socket[] sockets = new Socket[length];
		try {
			for (int i = 0; i < length; i++) {
				sockets[i] = new Socket(host, port);
				System.out.println("第" + (i + 1) + "次连接成功");
			}
			Thread.sleep(3000);
			for (int i = 0; i < length; i++) {
				sockets[i].close();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

class ServerBackLog implements Runnable {
	private int port = 8000;
	private ServerSocket serverSocket;

	public ServerBackLog() throws IOException {
		serverSocket = new ServerSocket(port, 3); // 连接请求队列的长度为3
		System.out.println("服务器启动");
	}

	public void service() {
		while (true) {
			Socket socket = null;
			try {
				socket = serverSocket.accept(); // 从连接请求队列中取出一个连接
				System.out.println("New connection accepted "
						+ socket.getInetAddress() + ":" + socket.getPort());
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (socket != null)
						socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public void run() {
		try {
			Thread.sleep(60000 * 10); // 睡眠10分钟
			//如果一直不accept取出backlog队列中的连接，超过3个就会队列满
			 //service();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}